import React, { useState, useEffect } from 'react';
import { Card, Tabs, Form, Input, Button, Switch, Select, Divider, message, Table, Tag } from 'antd';
import { SettingOutlined, UserOutlined, LockOutlined, BellOutlined, LogoutOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

const { TabPane } = Tabs;
const { Option } = Select;

const SystemSettings = () => {
  const navigate = useNavigate();
  const { userInfo } = useSelector((state) => state.auth);
  const [form] = Form.useForm();
  const [currentTab, setCurrentTab] = useState('basic');
  const [roles, setRoles] = useState([
    {
      id: '1',
      name: '管理员',
      permissions: ['all'],
      description: '系统管理员，拥有所有权限',
      status: 'active',
    },
    {
      id: '2',
      name: '运营人员',
      permissions: ['marketing', 'order'],
      description: '负责营销活动和订单管理',
      status: 'active',
    },
    {
      id: '3',
      name: '财务人员',
      permissions: ['finance'],
      description: '负责财务数据查看和管理',
      status: 'active',
    },
    {
      id: '4',
      name: '客服人员',
      permissions: ['customer_service'],
      description: '负责客户咨询和问题处理',
      status: 'inactive',
    },
  ]);
  const [users, setUsers] = useState([
    {
      id: '1',
      username: 'admin',
      email: 'admin@example.com',
      phone: '13800138000',
      roleId: '1',
      roleName: '管理员',
      status: 'active',
      createTime: '2024-01-01 00:00:00',
      lastLogin: '2024-04-12 15:30:45',
    },
    {
      id: '2',
      username: 'marketing',
      email: 'marketing@example.com',
      phone: '13800138001',
      roleId: '2',
      roleName: '运营人员',
      status: 'active',
      createTime: '2024-01-10 10:30:00',
      lastLogin: '2024-04-11 14:20:30',
    },
    {
      id: '3',
      username: 'finance',
      email: 'finance@example.com',
      phone: '13800138002',
      roleId: '3',
      roleName: '财务人员',
      status: 'active',
      createTime: '2024-01-15 14:00:00',
      lastLogin: '2024-04-10 09:45:12',
    },
  ]);
  const [emailSettings, setEmailSettings] = useState({
    host: 'smtp.example.com',
    port: 465,
    username: 'mail@example.com',
    password: '******',
    from: 'marketing@example.com',
    isSSL: true,
    isActive: true,
  });
  const [smsSettings, setSmsSettings] = useState({
    appId: 'APP123456',
    appKey: '******',
    templateId: 'SMS123456',
    isActive: false,
  });

  // 角色表格列定义
  const roleColumns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限范围',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions) => {
        const permissionMap = {
          'all': '全部权限',
          'marketing': '营销管理',
          'order': '订单管理',
          'finance': '财务管理',
          'customer_service': '客户服务',
        };
        return permissions.map((perm, index) => (
          <Tag key={index} color="blue">
            {permissionMap[perm] || perm}
          </Tag>
        ));
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'default'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button
            type="text"
            icon={<EditOutlined />}
            size="small"
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          {record.id !== '1' && (
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          )}
        </>
      ),
      width: 120,
    },
  ];

  // 用户表格列定义
  const userColumns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'default'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '上次登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button
            type="text"
            icon={<EditOutlined />}
            size="small"
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          {record.username !== 'admin' && (
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          )}
        </>
      ),
      width: 120,
    },
  ];

  // 初始化表单
  useEffect(() => {
    form.setFieldsValue({
      ...emailSettings,
    });
  }, []);

  // 处理标签页切换
  const handleTabChange = (key) => {
    setCurrentTab(key);
  };

  // 处理表单提交
  const handleSubmit = (values) => {
    console.log('Values:', values);
    message.success('设置保存成功');
  };

  // 处理密码修改
  const handlePasswordChange = () => {
    message.success('密码修改功能暂未实现');
  };

  // 添加角色
  const handleAddRole = () => {
    message.success('添加角色功能暂未实现');
  };

  // 添加用户
  const handleAddUser = () => {
    message.success('添加用户功能暂未实现');
  };

  // 登出系统
  const handleLogout = () => {
    // 在实际应用中，这里应该调用登出API
    message.success('已成功登出');
    setTimeout(() => {
      navigate('/login');
    }, 1000);
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>系统设置</h2>
        <p style={{ color: '#8c8c8c' }}>配置系统全局参数、用户权限和通知设置</p>
      </div>

      <Tabs activeKey={currentTab} onChange={handleTabChange}>
        {/* 基础设置 */}
        <TabPane tab={<><SettingOutlined /> 基础设置</>} key="basic">
          <Card bordered={false} style={{ borderRadius: 8 }}>
            <Form form={form} layout="vertical" onFinish={handleSubmit}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <Form.Item label="系统名称">
                  <Input defaultValue="营销中心管理系统" />
                </Form.Item>
                <Form.Item label="系统版本">
                  <Input value="v1.0.0" disabled />
                </Form.Item>
                <Form.Item label="系统语言">
                  <Select defaultValue="zh-CN">
                    <Option value="zh-CN">简体中文</Option>
                    <Option value="en-US">English</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="时间格式">
                  <Select defaultValue="YYYY-MM-DD HH:mm:ss">
                    <Option value="YYYY-MM-DD HH:mm:ss">年-月-日 时:分:秒</Option>
                    <Option value="MM/DD/YYYY HH:mm:ss">月/日/年 时:分:秒</Option>
                  </Select>
                </Form.Item>
              </div>

              <Divider style={{ margin: '24px 0' }} />

              <h3 style={{ marginBottom: 16 }}>安全设置</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <Form.Item label="密码有效期（天）">
                  <InputNumber min={0} defaultValue={90} />
                </Form.Item>
                <Form.Item label="登录失败次数限制">
                  <InputNumber min={0} defaultValue={5} />
                </Form.Item>
                <Form.Item label="会话超时时间（分钟）">
                  <InputNumber min={5} defaultValue={30} />
                </Form.Item>
                <Form.Item label="是否强制登录">
                  <Switch defaultChecked />
                </Form.Item>
              </div>

              <Divider style={{ margin: '24px 0' }} />

              <div style={{ textAlign: 'right' }}>
                <Button style={{ marginRight: 8 }}>取消</Button>
                <Button type="primary" htmlType="submit">保存设置</Button>
              </div>
            </Form>
          </Card>
        </TabPane>

        {/* 角色管理 */}
        <TabPane tab={<><LockOutlined /> 角色管理</>} key="roles">
          <Card bordered={false} style={{ borderRadius: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
              <h3>角色列表</h3>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddRole}>
                添加角色
              </Button>
            </div>
            <Table
              columns={roleColumns}
              dataSource={roles}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              rowKey="id"
            />
          </Card>
        </TabPane>

        {/* 用户管理 */}
        <TabPane tab={<><UserOutlined /> 用户管理</>} key="users">
          <Card bordered={false} style={{ borderRadius: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
              <h3>用户列表</h3>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
                添加用户
              </Button>
            </div>
            <Table
              columns={userColumns}
              dataSource={users}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              rowKey="id"
            />
          </Card>
        </TabPane>

        {/* 通知设置 */}
        <TabPane tab={<><BellOutlined /> 通知设置</>} key="notifications">
          <Card bordered={false} style={{ borderRadius: 8 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
              <div>
                <h3 style={{ marginBottom: 16 }}>邮件通知设置</h3>
                <Form layout="vertical">
                  <Form.Item label="邮件服务器地址">
                    <Input value={emailSettings.host} onChange={(e) => setEmailSettings({ ...emailSettings, host: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="邮件服务器端口">
                    <InputNumber min={1} max={65535} value={emailSettings.port} onChange={(value) => setEmailSettings({ ...emailSettings, port: value })} />
                  </Form.Item>
                  <Form.Item label="用户名">
                    <Input value={emailSettings.username} onChange={(e) => setEmailSettings({ ...emailSettings, username: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="密码">
                    <Input.Password value={emailSettings.password} onChange={(e) => setEmailSettings({ ...emailSettings, password: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="发件人邮箱">
                    <Input value={emailSettings.from} onChange={(e) => setEmailSettings({ ...emailSettings, from: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="SSL加密">
                    <Switch checked={emailSettings.isSSL} onChange={(checked) => setEmailSettings({ ...emailSettings, isSSL: checked })} />
                  </Form.Item>
                  <Form.Item label="启用邮件通知">
                    <Switch checked={emailSettings.isActive} onChange={(checked) => setEmailSettings({ ...emailSettings, isActive: checked })} />
                  </Form.Item>
                  <div style={{ textAlign: 'right' }}>
                    <Button type="primary" onClick={() => message.success('邮件设置保存成功')}>保存设置</Button>
                  </div>
                </Form>
              </div>
              
              <div>
                <h3 style={{ marginBottom: 16 }}>短信通知设置</h3>
                <Form layout="vertical">
                  <Form.Item label="应用ID">
                    <Input value={smsSettings.appId} onChange={(e) => setSmsSettings({ ...smsSettings, appId: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="应用密钥">
                    <Input.Password value={smsSettings.appKey} onChange={(e) => setSmsSettings({ ...smsSettings, appKey: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="短信模板ID">
                    <Input value={smsSettings.templateId} onChange={(e) => setSmsSettings({ ...smsSettings, templateId: e.target.value })} />
                  </Form.Item>
                  <Form.Item label="启用短信通知">
                    <Switch checked={smsSettings.isActive} onChange={(checked) => setSmsSettings({ ...smsSettings, isActive: checked })} />
                  </Form.Item>
                  <div style={{ textAlign: 'right' }}>
                    <Button type="primary" onClick={() => message.success('短信设置保存成功')} disabled={!smsSettings.isActive}>保存设置</Button>
                  </div>
                </Form>
              </div>
            </div>
          </Card>
        </TabPane>

        {/* 个人设置 */}
        <TabPane tab={<><UserOutlined /> 个人设置</>} key="profile">
          <Card bordered={false} style={{ borderRadius: 8 }}>
            <h3 style={{ marginBottom: 24 }}>个人信息</h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <p style={{ color: '#8c8c8c' }}>用户名</p>
                <p style={{ fontWeight: 'bold' }}>{userInfo?.username || 'admin'}</p>
              </div>
              <div>
                <p style={{ color: '#8c8c8c' }}>邮箱</p>
                <p>{userInfo?.email || 'admin@example.com'}</p>
              </div>
              <div>
                <p style={{ color: '#8c8c8c' }}>手机号</p>
                <p>{userInfo?.phone || '13800138000'}</p>
              </div>
              <div>
                <p style={{ color: '#8c8c8c' }}>角色</p>
                <p>{userInfo?.role || '管理员'}</p>
              </div>
              <div>
                <p style={{ color: '#8c8c8c' }}>创建时间</p>
                <p>2024-01-01 00:00:00</p>
              </div>
              <div>
                <p style={{ color: '#8c8c8c' }}>上次登录</p>
                <p>2024-04-12 15:30:45</p>
              </div>
            </div>

            <Divider style={{ margin: '32px 0' }} />

            <h3 style={{ marginBottom: 16 }}>修改密码</h3>
            <Form layout="vertical" onFinish={handlePasswordChange}>
              <div style={{ maxWidth: '50%' }}>
                <Form.Item
                  name="currentPassword"
                  label="当前密码"
                  rules={[{ required: true, message: '请输入当前密码' }]}
                >
                  <Input.Password placeholder="请输入当前密码" />
                </Form.Item>
                <Form.Item
                  name="newPassword"
                  label="新密码"
                  rules={[{ required: true, message: '请输入新密码' }]}
                >
                  <Input.Password placeholder="请输入新密码" />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  label="确认新密码"
                  rules={[{ required: true, message: '请确认新密码' }]}
                >
                  <Input.Password placeholder="请确认新密码" />
                </Form.Item>
                <div style={{ textAlign: 'right' }}>
                  <Button type="primary" htmlType="submit">修改密码</Button>
                </div>
              </div>
            </Form>

            <Divider style={{ margin: '32px 0' }} />

            <div style={{ textAlign: 'right' }}>
              <Button
                type="primary"
                danger
                icon={<LogoutOutlined />}
                onClick={handleLogout}
              >
                退出登录
              </Button>
            </div>
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default SystemSettings;